﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Text.RegularExpressions;
using EcodexIntegrationSample.View;
using System.Configuration;

namespace EcodexIntegrationSample.Utils
{
    class Utilerias
    {
        /// <summary>
        /// This id can come from a database or be hard coded 
        /// by each service integrator or service reseller.
        /// </summary>
        public String INTEGRATOR_ID = "2b3a8764-d586-4543-9b7e-82834443f219";
        public String AltaIntegrador_ID = "DF627BC3-A872-4806-BF37-DBD040CBAC7C";

        public string RFC = "AAA010101AAA";
        public String NoCertificado = "20001000000100005868";

        //public string RFC = "PNU1111251F3";
        //public string RFC = "SUL010720JN8";
        public const String ErrorRFCInvalido = "El RFC es un rfc no válido";

        public String urlApi
        {
            get
            {
                return ConfigurationManager.AppSettings["UrlApi"];
            }
        }

        public String urlAltaCertificados
        {
            get
            {
                return ConfigurationManager.AppSettings["UrlAltaCertificados"];
            }
        }

        private IInterface _view;
        public Utilerias()
        {
            _view = null;
        }
        public Utilerias(IInterface Inter)
        {
            _view = Inter;
        }
        public string CreateToken(string RFC, Int64 transactionID, ref string token)
        {
            string result = string.Empty;
            try
            {
                if (!ValidarRFCEmisor(RFC))
                {                    
                    using (var errorForm = new Forms.Error(GeneraErrorLocal(ErrorRFCInvalido, RFC)))
                    {
                        errorForm.ShowDialog();
                        return ErrorRFCInvalido;
                    }   
                }

                #region Build Token
                using (var securitySrv = new SrvSecurity.SeguridadClient())
                {
                    var serviceToken = securitySrv.ObtenerToken(RFC, ref transactionID);
                    var toHash = String.Format("{0}|{1}", INTEGRATOR_ID, serviceToken);
                    token = Security.Hash(toHash);
                }
                #endregion
            }
            #region Security service exceptions
            catch (FaultException<SrvSecurity.FallaServicio> serviceFault)
            {
                using (var errorForm = new Forms.Error(TranslateFault.ToServiceError(serviceFault.Detail)))
                {
                    errorForm.ShowDialog();
                }
            }
            catch (FaultException<SrvSecurity.FallaSesion> sessionFauld)
            {
                _view.ShowSessionError(TranslateFault.ToSessionError(sessionFauld.Detail));
                result = TranslateFault.ToSessionError(sessionFauld.Detail).Description;
            }
            #endregion
            catch (Exception ex)
            {
                _view.ShowUnknownError(ex.Message);
                result = ex.Message;
            }
            return result;
        }

        public string CreateTokenAlta(string RFC, Int64 transactionID, ref string token)
        {
            string result = string.Empty;
            try
            {
                #region Build Token
                using (var securitySrv = new SrvSecurity.SeguridadClient())
                {
                    var serviceToken = securitySrv.ObtenerToken(RFC, ref transactionID);
                    var toHash = String.Format("{0}|{1}|{2}", INTEGRATOR_ID,AltaIntegrador_ID, serviceToken);
                    token = Security.Hash(toHash);
                }
                #endregion
            }
            #region Security service exceptions
            catch (FaultException<SrvSecurity.FallaServicio> serviceFault)
            {
                using (var errorForm = new Forms.Error(TranslateFault.ToServiceError(serviceFault.Detail)))
                {
                    errorForm.ShowDialog();
                }
            }
            catch (FaultException<SrvSecurity.FallaSesion> sessionFauld)
            {
                _view.ShowSessionError(TranslateFault.ToSessionError(sessionFauld.Detail));
                result = TranslateFault.ToSessionError(sessionFauld.Detail).Description;
            }
            #endregion
            catch (Exception ex)
            {
                _view.ShowUnknownError(ex.Message);
                result = ex.Message;
            }
            return result;
        }

        public bool ValidarRFCEmisor(String RFC)
        {
            Regex rgx = new Regex(@"^[A-Z,Ñ,&]{3,4}[0-9]{2}[0-1][0-9][0-3][0-9][A-Z,0-9]{2}[0-9,A]{1}$");            
            return rgx.IsMatch(RFC);
        }

        public Entity.ValidationError GeneraErrorLocal(String Mensaje, String RFC)
        {
            Entity.ValidationError validacionError = new Entity.ValidationError();
            validacionError.RFC = RFC;
            validacionError.Description = Mensaje;
            validacionError.Number = 12;
            return validacionError;
        }
    }
}
